package safe;

/**
 * wait()和notify()    等待和通知
 * 用来处理线程调度随机性的问题
 * 调用wait方法的线程,就会进入阻塞状态,进入阻塞后,等待notify()来通知
 *
 * wait操作会做三件事:
 * 1. 先释放锁
 * 2. 等待其他进程的通知
 * 3. 收到通知后,重新获取锁,并继续往下执行
 *
 * notifyAll()用于唤醒所有的线程,但是会造成竞争
 */

public class Demo5 {

    private static Object locker = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            // 进行 wait
            synchronized (locker) {
                System.out.println("wait 之前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("wait 之后");
            }
        });
        t1.start();

        Thread.sleep(3000);
        System.out.println(t1.getState());


        Thread t2 = new Thread(() -> {
            // 进行 notify
            synchronized (locker) {
                System.out.println("notify 之前");
                locker.notify();
                System.out.println("notify 之后");
            }
        });
        t2.start();
    }

    public static void main1(String[] args) throws InterruptedException {
        Object ob = new Object();
        synchronized (ob){//wait哪个对象,就得对哪个对象加锁~
            System.out.println("wait前");
            ob.wait();
            System.out.println("wait后");
        }
    }
}
